package com.dubbo.server.controller;


import com.dubbo.server.service.UserService;
import com.dubbo.server.vo.ErrorResult;
import com.tanhua.common.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param param
     * @return
     */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        try {
            // 手机号码
            String phone = param.get("phone");
            // 验证码
            String code = param.get("verificationCode");
            if (phone == null || phone == "") {
                ErrorResult errorResult = ErrorResult.builder().errCode("000003").errMessage("手机号不合法或者为空！").build();
                // 如果异常了就响应一个500和错误信息
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
            }
            if (code == null || code == "") {
                ErrorResult errorResult = ErrorResult.builder().errCode("000003").errMessage("验证码不合法或者为空！").build();
                // 如果异常了就响应一个500和错误信息
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
            }
            // 调用Service实现验证码的登录功能
            Map data = this.userService.login(phone, code);

            if (data != null) {
                return ResponseEntity.ok(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败！").build();
        // 如果异常了就响应一个500和错误信息
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }



    /**
     * 校验token，根据token查询用户数据
     * http://localhost:18080/user/xxxxx
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }

}
